<template>
  <div class='container'>
    <el-dialog :title="showTitle" :visible="showDialog" width="40%"  @close="close">
      <!-- 表单 -->
      <el-form ref="form" label-width="120px" :model="form" :rules="rules">
        <el-form-item label="学科名称" prop="subjectName" id="subjectNameID">
          <el-input v-model="form.subjectName" placeholder="请输入学科名称" ref="input"/>
        </el-form-item>
        <el-form-item label="是否显示" prop="isFrontDisplay">
            <el-switch
              v-model="form.isFrontDisplay"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value=1
              :inactive-value=0
            />
        </el-form-item>
      </el-form>
      <!-- footer插槽 -->
      <template v-slot:footer>
        <el-button size="small" @click="close">取消</el-button>
        <el-button type="primary" size="small" @click="addSubjects">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/subjects.js'
export default {
  props: {
    showDialog: {
      type: Boolean,
      required: false
    }
  },
  data () {
    return {
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称' }
        ],
        isFrontDisplay: [
          { required: true, message: '请输入学科名称' }
        ]
      },
      form: {
        subjectName: '',
        isFrontDisplay: 1,
        id: ''
      }
    }
  },
  computed: {
    showTitle () {
      return this.form.id ? '修改学科' : '新增学科'
    }
  },

  methods: {
    // 关闭弹窗d
    ref () {
      document.getElementById('input').focus()
    },
    close () {
      this.$emit('closeShowDialog', false)
      this.$refs.form.resetFields()
    },
    // 新增学科
    async addSubjects () {
      try {
        await this.$refs.form.validate()
      } catch {
        return
      }
      if (this.form.id) {
        // const { id, subjectName, isFrontDisplay } = this.subjectDate
        // this.form = { id, subjectName, isFrontDisplay }
        await update({ ...this.form })
        this.$message.success('修改学科成功')
      } else {
        await add({ ...this.form })
        this.$message.success('新增学科成功')
      }
      // 重新渲染 关闭弹窗
      this.$parent.getList()
      this.$emit('update:showDialog', false)
    }
  }
}
</script>

<style scoped lang='less'></style>
